package com.core.sgip.common;

import java.util.List;

import com.core.sgip.common.body.SGIPCommand;
import com.core.sgip.common.body.command.Deliver;
import com.core.sgip.common.body.command.Submit;
import com.core.sgip.common.factory.SGIPFactory;
import com.core.sgip.common.head.SGIPMsgHead;
import com.core.sgip.interf.SGIPByteData;

public class SGIPMsg implements SGIPByteData {

	private SGIPMsgHead head;

	private SGIPCommand command;

	public SGIPMsgHead getHead() {
		return head;
	}

	public void setHead(SGIPMsgHead head) {
		this.head = head;
	}

	public SGIPCommand getCommand() {
		return command;
	}

	public void setCommand(SGIPCommand command) {
		this.command = command;
	}

	private void calcute() {
		long messageLength = this.command.getCommandLength() + SGIPMsgHead.HEAD_LENGTH;
		this.head.setMessageLength(messageLength);
	}

	@Override
	public byte[] getByteData() {
		byte[] commandBytes = command.getByteData();
		calcute();
		return SGIPUtils.mergeBytes(head.getByteData(), commandBytes);
	}
	public byte[] getByteDatareport(String seq) {
		byte[] commandBytes = command.getByteDatareport(seq);
		calcute();
		return SGIPUtils.mergeBytes(head.getByteDatasubmitresp(seq), commandBytes);
	}
	public byte[] getByteDatasubmitresp(String seq) {
		byte[] commandBytes = command.getByteData();
		calcute();
		return SGIPUtils.mergeBytes(head.getByteDatasubmitresp(seq), commandBytes);
	}
	
	public void setUserNumbers(List<String> listUserNumber, String messageContent) {
//		if (head == null || command == null || head.getCommandId() != SGIPConstant.SGIP_SUBMIT) {
//			return;
//		}
		Submit sub = (Submit) command;
		sub.setListUserNumber(listUserNumber);
		sub.setMessageContent(messageContent);
	}
	public void setUserNumbers(String userNumber, String messageContent) {
		if (head.getCommandId()  == SGIPConstant.SGIP_DELIVER) {
			Deliver sub = (Deliver) command;
			sub.setUserNumber(userNumber);
			sub.setMessageContent(messageContent);
		}
	}

	private void initHead(byte[] source) {
		head = new SGIPMsgHead();
		byte[] headByte = new byte[SGIPMsgHead.HEAD_LENGTH];
		SGIPUtils.copyBytes(source, headByte, 1, SGIPMsgHead.HEAD_LENGTH, 1);
		head.initPropertiesByBytes(headByte);
	}

	private void initCommand(byte[] source) throws Exception {
		if (head == null || head.getCommandId() == null) {
			return;
		}
		long commandId = head.getCommandId();
		command = SGIPFactory.getCommandByCommandId(commandId);
		int bytelen = source.length - SGIPMsgHead.HEAD_LENGTH;
		byte[] commandByte = new byte[bytelen];
		SGIPUtils.copyBytes(source, commandByte, SGIPMsgHead.HEAD_LENGTH + 1, commandByte.length, 1);
		command.initPropertiesByBytes(commandByte);
	}

	@Override
	public void initPropertiesByBytes(byte[] source) {
		initHead(source);
		try {
			initCommand(source);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return "SGIPMsg [head=" + head + ", command=" + command + "]";
	}
}
